package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单的定时任务处理
 */

@Slf4j
@Component

public class OrderTask {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 超时订单未支付
     */
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void processOutTimeOrder(){
        log.info("<超时订单未支付>");
        //首先超时订单未支付查询
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.selectByStatusAndTime(Orders.PENDING_PAYMENT , time);

        //其次，如果存在遍历修改订单的状态为已取消
        if (ordersList !=null || ordersList.size()>0){
            ordersList.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("超时订单且未支付,订单取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }

    }

    /**
     * 定时处理派送中的订单
     *
     */
    //测试使用
    //@Scheduled(cron = "0 8 12 * * ? ")
    @Scheduled(cron = "0 0 1 * * ? " )
    public void processDeliveryingOrder(){
        log.info("<<定时处理派送中的订单>>");
        //查询订单状态,要避免最近一个小时的订单不要处理   下单时间 < 当前时间 - 60分钟的进行处理
        LocalDateTime time = LocalDateTime.now().minusHours(1);

        List<Orders> ordersList =  orderMapper.selectByStatusAndTime(Orders.DELIVERY_IN_PROGRESS,time);


        //修改订单状态
        if (ordersList !=null || ordersList.size()>0){
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }

    }



}
